package cn.lan.generator.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.PatternPool;
import cn.hutool.core.util.StrUtil;
import cn.lan.generator.bean.Module;
import cn.lan.generator.bean.ProjInfo;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.net.URLDecoder;
import java.util.Map;
import java.util.regex.Matcher;

/**
 * @author lanping
 * @version 1.0
 * @date 2019-06-30
 **/
public class FileUtil {

    /**
     * 替换文件中的内容，复制文件 返回文件内容
     * @param srcFilePath 模板路径
     * @param map
     */
    public static String copyFile(String srcFilePath, Map<String,String> map){
        StringBuffer stringBuffer = new StringBuffer();
        try {
            FileReader reader = new FileReader(srcFilePath);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                line = replaceStrByMap(line, map);
                stringBuffer.append(line+"\r\n");
            }
            reader.close();
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    /**
     * 替换文件中的内容，复制文件
     * @param srcFilePath
     * @param destFilePath
     * @param map
     */
    public static void copyFile(ProjInfo projInfo,String srcFilePath, String destFilePath, Map<String,String> map){
        String rootDir = projInfo.getCreateProjectUrl();
        //调试模式 直接生成在项目目录
        if(projInfo.isDebugModel()){

            String projectPath  = FileUtil.class.getClassLoader().getResource("").getPath();
            try {
                projectPath = URLDecoder.decode(projectPath, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            projectPath = projectPath.replace("target/test-classes/", "")
            .replace("target/classes/","");

            destFilePath = destFilePath.replace(rootDir, projectPath);
        }
        destFilePath = destFilePath.replaceAll("\\\\","/");

        File file = new File(destFilePath);
        file.getParentFile().mkdirs();
        if (file.exists()) {
            System.out.println(Constant.warnMsg + destFilePath + " 已存在");
            return;
        }

        System.out.println(DateUtil.now() + " " + destFilePath);
        try {
            FileReader reader = new FileReader(srcFilePath);
            BufferedReader bufferedReader = new BufferedReader(reader);

            File outFile = new File(destFilePath);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            FileWriter writer = new FileWriter(outFile);
            BufferedWriter bufferedWriter = new BufferedWriter(writer);

            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                line = replaceStrByMap(line, map);
                bufferedWriter.write(line);
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }
            writer.close();
            reader.close();
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String replaceStrByMap(String str,Map<String,String> map){
        Matcher m= PatternPool.get("\\$\\{(\\w+)\\}").matcher(str);
        while(m.find()){
            String group = m.group();
            if(map.containsKey(m.group(1))){
                String value = StrUtil.isBlank(map.get(m.group(1)))?"":map.get(m.group(1));
                str=str.replace(group,value);
            }
        }
        return str;
    }

    /**
     * 复制文件或文件夹
     * @param srcPath
     * @param destPath
     */
    public static void copyFile(ProjInfo projInfo,String srcPath, String destPath){

        //调试模式 直接生成在项目目录
        if(projInfo.isDebugModel()){

            String rootDir = projInfo.getCreateProjectUrl();

            String projectPath  = FileUtil.class.getClassLoader().getResource("").getPath();
            try {
                projectPath = URLDecoder.decode(projectPath, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            projectPath = projectPath.replace("target/test-classes/", "")
                    .replace("target/classes/","");

            destPath = destPath.replace(rootDir, projectPath);
        }
        destPath = destPath.replaceAll("\\\\","/");

        System.out.println(DateUtil.now() + " " + destPath);
        new File(destPath).getParentFile().mkdirs();
        //复制该文件夹下的所有文件
        cn.hutool.core.io.FileUtil.copy(srcPath,destPath,true);
    }

    /**
     * 写文件
     * @param content
     * @param destPath
     */
    public static void writeFile(ProjInfo projInfo,String content, String destPath){

        //调试模式 直接生成在项目目录
        if(projInfo.isDebugModel()){

            String rootDir = projInfo.getCreateProjectUrl();

            String projectPath  = FileUtil.class.getClassLoader().getResource("").getPath();
            try {
                projectPath = URLDecoder.decode(projectPath, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            projectPath = projectPath.replace("target/test-classes/", "")
                    .replace("target/classes/","");

            destPath = destPath.replace(rootDir, projectPath);
        }
        destPath = destPath.replaceAll("\\\\","/");
        System.out.println(DateUtil.now() + " " + destPath);
        File file = new File(destPath);
        file.getParentFile().mkdirs();
        cn.hutool.core.io.FileUtil.writeString(content,file,"UTF-8");
    }

    /**
     * 获取资源根路径
     * @return
     */
    public static String getResourceRootDir(boolean debug){
        String path = "";
        if(debug){
            path  = FileUtil.class.getClassLoader().getResource("").getPath();
            try {
                path = URLDecoder.decode(path, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            path = path.replace("/target/test-classes/", "/target/classes/");
        }else{
            path = ConfigUtil.getConfigValue(Constant.KEY_TEMPLATE_DIR);
        }
        return path;
    }

    /**
     * 结束操作
     * @param projInfo
     * @throws IOException
     */
    public static void finishWrite(ProjInfo projInfo) throws IOException {
        //如果是生成zip
        if(projInfo.isCreateZIPFile()){
            //压缩文件
            String rootDir = projInfo.getCreateProjectUrl();
            String outZipPath = rootDir + projInfo.getProjectName() + Constant.FILE_SUFFIX_ZIP;
            File file = new File(outZipPath);
            if(file.exists()){
                file.delete();
            }
            FileOutputStream fos1 = new FileOutputStream(file);
            ZipUtil.toZip(rootDir + projInfo.getProjectName(), fos1, true);

            //删除文件夹
            File directory = new File(rootDir + projInfo.getProjectName());
            FileUtils.deleteDirectory(directory);

            System.out.println("执行成功，"+outZipPath+"已生成，请查看！");
        }else{
            System.out.println("执行成功，请刷新项目！");
        }
        Module.setEmptyModule();
    }
}
